<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="query.query.materialName" placeholder="请输入商品名称" clearable @keyup.enter.native="search" />
      <el-input v-model="query.query.materialNo" placeholder="请输入商品代码" clearable @keyup.enter.native="search" />
      <el-select v-model="query.query.state" clearable placeholder="请选择商品状态" filterable>
        <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" icon="el-icon-search" @click="search">{{ $t('table.search') }}</el-button>
      <el-button type="primary" icon="el-icon-upload2" @click="importExport">导入</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <!-- 1 -->
      <!-- <el-table-column prop="supplierId" label="供应商" sortable>
        <template slot-scope="{row:{supplierId}}">
          {{ supplierId && partnersData.find(type => type.id == supplierId) && partnersData.find(type => type.id ==
            supplierId).partnerName }}
        </template>
      </el-table-column> -->
      <el-table-column prop="materialNo" label="物料代码" sortable />
      <el-table-column prop="materialName" label="物料名称" sortable />
      <el-table-column prop="materialCategory" label="物料品类" sortable />
      <el-table-column prop="model" label="颜色" sortable />
      <el-table-column prop="standard" label="规格" sortable />
      <el-table-column prop="unit" label="单位" sortable />
      <el-table-column prop="packageStandard" label="包装规格" sortable />
      <el-table-column prop="safeStock" label="安全库存" sortable />
      <el-table-column prop="minPackage" label="最小采购数量" sortable />
      <el-table-column prop="untaxedUnitPrice" label="未税单价" sortable />
      <el-table-column prop="includingTaxPrice" label="含税价格" sortable />
      <el-table-column prop="taxRate" label="税率" sortable />
      <el-table-column prop="state" label="状态" sortable>
        <template slot-scope="{row:{state}}">
          <el-tag :type="state == 1 ? 'success' : 'danger'">{{ state == 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="150">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">{{ $t('table.edit') }}</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="query.pageIndex" :limit.sync="query.pageSize"
      @pagination="getInfo" />
    <el-dialog :close-on-click-modal="false" :visible.sync="dialogVisible" :title="store.id ? '编辑' : '新增'"
      @closed="dialogClosed">
      <el-form :model="store" ref="ruleForm" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料代码" prop="materialNo">
              <el-input v-model="store.materialNo" clearable placeholder="请输入物料代码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="store.materialName" clearable :disabled="store.id" placeholder="请输入物料名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料品类" prop="materialCategory">
              <el-input v-model="store.materialCategory" clearable :disabled="store.id" placeholder="请输入物料品类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格" prop="standard">
              <el-input v-model="store.standard" clearable placeholder="请输入规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="颜色" prop="model ">
              <el-input v-model="store.model" clearable placeholder="请输入颜色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包装规格" prop="packageStandard">
              <el-input v-model="store.packageStandard" clearable placeholder="请输入包装规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="store.unit" clearable placeholder="请输入单位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未税单价" prop="untaxedUnitPrice">
              <el-input v-model="store.untaxedUnitPrice" clearable @input="handleUntaxedUnitPrice"
                placeholder="请输入未税单价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="安全库存" prop="safeStock">
              <el-input v-model="store.safeStock" clearable placeholder="请输入安全库存" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税单价" prop="includingTaxPrice">
              <el-input v-model="store.includingTaxPrice" clearable placeholder="请输入含税单价"
                @input="handleIncludingTaxPrice" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供应商" prop="supplierId">
              <el-select style="width: 100%;" v-model="store.supplierId" clearable placeholder="请选择供应商" filterable>
                <el-option v-for="item in partnersData" :key="item.id" :label="item.partnerName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最小采购数量">
              <el-input v-model="store.minPackage" clearable placeholder="请输入最小采购数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率" prop="taxRate">
              <el-input v-model="store.taxRate" onkeyup="value=value.replace(/[^\d|\.]/g, '')" @input="handleTaxRate"
                clearable placeholder="请输入税率">
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
         <el-col :span="12" v-if="!store.id">
            <el-form-item label="初始仓库" prop="warethouseId">
              <el-select style="width: 100%;" v-model="store.warethouseId" clearable placeholder="请选择初始仓库" filterable>
                <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="store.state" size="small">
                <el-radio-button v-for="state in statusList" :key="state.value" :label="state.value">
                  {{ state.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="dialogVisible = false">{{ $t('permission.cancel') }}</el-button>
        <el-button type="primary" @click="confirm">{{ $t('permission.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导入商品" width="400px" :visible.sync="importExportVisible" @closed="handleClose" :close-on-click-modal="false">
      <div>
        <el-button type="text" @click="downloadExcel">下载模版</el-button>
        <el-upload ref="elUpload" drag :auto-upload="false" action="#" :limit="1" :on-change="handleChange"
          :on-remove="handleRemove">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importExportVisible = false">取 消</el-button>
        <el-button type="primary" @click="importExportSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { materialPageList, materialAdd, materialModify, materialDel, materialImport } from '@/api/departentment'
import { partnersList } from '@/api/customerforecast'
import { warehousePageList } from '@/api/qmsQualityManagement'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { downLoadTemplate } from '../../../utils'
import math from "@/utils/math";
const defaultStore = () => {
  return {
    materialType: '2',
    state: '1',
    untaxedUnitPrice: '',
    taxRate: '',
    includingTaxPrice: ''
  }
}

export default {
  name: 'Store',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      multiply: math.multiply, //乘法
      subtract: math.subtract, //减法
      divide: math.divide, //除法
      add: math.add,//加法
      importExportForm: defaultStore(),
      importExportVisible: false,
      statusList: [{
        label: '启用',
        value: '1'
      }, {
        label: '禁用',
        value: '0'
      }],
      realName: '',
      value: [],
      dialogVisible: false,
      total: 0,
      store: defaultStore(),
      query: {
        pageIndex: 1,
        pageSize: 20,
        query: {
          materialName: '',
          materialNo: '',
          materialType: '2',
          state: ""
        }
      },
      tableData: [],
      supplierList: [],
      rules: {
        materialName: [
          { required: true, message: '请输入物料名称', trigger: 'blur' }
        ],
        // materialNo: [
        //   { required: true, message: '请输入商品代码', trigger: 'blur' }
        // ],
        // safeStock: [
        //   { required: true, message: '请输入安全', trigger: 'blur' }
        // ],
        // supplierId: [
        //   { required: true, message: '请选择供应商', trigger: 'change' }
        // ],
        // unit: [
        //   { required: true, message: '请输入单位', trigger: 'blur' }
        // ],
        // untaxedUnitPrice: [
        //   { required: true, message: '请输入未税单价', trigger: 'blur' }
        // ],
        // taxRate: [
        //   { required: true, message: '请输入税率', trigger: 'blur' }
        // ],
        // includingTaxPrice: [
        //   { required: true, message: '请输入含税单价', trigger: 'blur' }
        // ],
        // warethouseId: [
        //   { required: true, message: '请选择初始仓库', trigger: 'change' }
        // ]
      },
      partnersData: [],
      warehouseList: []
    }
  },
  mounted() {
    this.getInfo()
    this.getPartnersList()
    this.getWarehousePageList()
  },
  methods: {
    handleUntaxedUnitPrice(e) {
      const { includingTaxPrice: unitTaxedPrice, taxRate: taxRateRounded } = this.store
      if (!Number(e) || (!Number(unitTaxedPrice) && !Number(taxRateRounded))) return
      if ((Number(unitTaxedPrice) && Number(taxRateRounded)) || Number(taxRateRounded)) {
        const includingTaxPrice = this.multiply(Number(e), this.add(1, this.divide(Number(taxRateRounded), 100)))
        this.store.includingTaxPrice = Number(includingTaxPrice).toFixed(2)
      } else if (Number(unitTaxedPrice)) {
        const taxRate = this.multiply(this.divide(this.subtract(Number(unitTaxedPrice), Number(e)), Number(e)), 100)
        this.store.taxRate = Number(taxRate).toFixed(2)
      }
    },
    handleIncludingTaxPrice(e) {
      const { untaxedUnitPrice: price, taxRate: taxRateRounded } = this.store
      if (!Number(e) || (!Number(price) && !Number(taxRateRounded))) return
      if ((Number(price) && Number(taxRateRounded)) || Number(taxRateRounded)) {
        const untaxedUnitPrice = this.divide(Number(e), this.add(1, this.divide(Number(taxRateRounded), 100)))
        this.store.untaxedUnitPrice = Number(untaxedUnitPrice).toFixed(2)
      } else if (Number(price)) {
        const taxRate = this.multiply(this.divide(this.subtract(Number(e), Number(price)), Number(price)), 100)
        this.store.taxRate = Number(taxRate).toFixed(2)
      }
    },
    handleTaxRate(e) {
      const { untaxedUnitPrice: price, includingTaxPrice: unitTaxedPrice } = this.store
      if (!Number(e) || (!Number(price) && !Number(unitTaxedPrice))) return
      if ((Number(price) && Number(unitTaxedPrice)) || Number(price)) {
        const includingTaxPrice = this.multiply(Number(price), this.add(1, this.divide(Number(e), 100)))
        this.store.includingTaxPrice = Number(includingTaxPrice).toFixed(2)
      } else if (Number(unitTaxedPrice)) {
        const untaxedUnitPrice = this.divide(Number(unitTaxedPrice), this.add(1, Number(e)))
        this.store.untaxedUnitPrice = Number(untaxedUnitPrice).toFixed(2)
      }
    },
    getWarehousePageList() {
      warehousePageList({
        query: { state: "1" }
      }).then(res => {
        this.warehouseList = res
      })
    },
    async getPartnersList() {
      const { records } = await partnersList({
        pageIndex: 1,
        pageSize: 100000,
        query: {
          partnerType: '2'
        }
      })
      this.partnersData = records
    },
    handleClose() {
      this.$refs['elUpload'].clearFiles()
    },
    async importExportSure() {
      try {
        if (!this.importExportForm.file) {
          this.$message.warning('请先上传商品数据')
          return false
        }
        const formData = new FormData()
        for (let key in this.importExportForm) {
          formData.append(key, this.importExportForm[key])
        }
        await materialImport(formData)
        this.getInfo()
        this.$message.success('导入成功')
        this.importExportVisible = false
      } catch (err) {
        this.handleRemove()
        this.$refs['elUpload'].clearFiles()
      }
    },
    handleChange(file, fileList) {
      this.importExportForm.file = file.raw
    },
    handleRemove() {
      this.importExportForm.file = ''
    },
    downloadExcel() {
      downLoadTemplate('商品导入模版.xlsx', '商品导入模版.xlsx')
    },
    dialogClosed() {
      this.store = defaultStore()
      this.$refs['ruleForm'].resetFields();
    },
    async getInfo() {
      const { records, total } = await materialPageList(this.query)
      this.tableData = records
      this.total = total
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    importExport() {
      this.importExportVisible = true
    },
    handleAdd() {
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.dialogVisible = true
      this.store = Object.assign({}, row)
    },
    handleDelete(row) {
      this.$confirm('确认删除?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await materialDel(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getInfo()
        })
    },
    confirm() {
      this.$refs['ruleForm'].validate(async valid => {
        if (valid) {
          const httpFn = this.store.id ? materialModify : materialAdd
          await httpFn(this.store)
          this.getInfo()
          this.$message.success('操作成功')
          this.dialogVisible = false
          this.store = defaultStore()
        }
      })
    }
  }
}
</script>
